<template>
  <section>
    <!--卡牌-->
    <el-card class="box-card" v-if="! allTaskDetail">
      <div class="text item">
        <span>模板名称 : </span>
        <span>{{infos.user_task_name}}</span>
      </div>
      <div class="text item">
        <span>类型 : </span>
        <span>{{infos.task_run_component_type | taskType}}</span>
      </div>
      <div class="text item">
        <span>创建时间 : </span>
        <span>{{infos.create_time}}</span>
      </div>
      <div class="text item">
        <span>用户 : </span>
        <span>{{infos.user_name}}</span>
      </div>
      <!--  </div><div class="text item">
            <span>角色 : </span>
            <el-tag v-for="item in infos.role_names||[]" type="primary">{{item}}</el-tag>
        </div>-->
      <!--<div class="text item">
          <span>操作 : </span>
          <el-button size="large" type="text" @click="toCGStart">{{start | toSta}}</el-button>
      </div>-->
    </el-card>
    <!--工具条-->
    <el-col :span="24" class="toolbar" v-if="allTaskDetail">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @blur="search"></Search>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table
      v-loading="listLoading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <!-- <el-table-column prop="task_real_id" label="ApplicationID">
         <template scope="scope">
           <span v-if ="taskType==7">{{scope.row.task_real_id}}</span>
           <router-link v-else
             :to="{path:`/${toPageOfTbId}` , query:{task_real_id:`${scope.row.task_real_id}`,user_task_detail_id:`${scope.row.user_task_detail_id}` ,task_run_component_type:`${infos.task_run_component_type}` } }">
             {{scope.row.task_real_id}}
           </router-link>
         </template>
       </el-table-column>-->

      <el-table-column
        prop="user_task_detail_id"
        label="Id">
        <template scope="scope">
          <span v-if="scope.row.task_run_component_type==7">{{scope.row.user_task_detail_id}}</span>
          <span v-else>
            <router-link v-if="scope.row.task_run_component_type==6"
                         :to="{path:`/${getTopageByID(scope.row)}` , query:{task_real_id:`${scope.row.task_real_id}`,user_task_detail_id:`${scope.row.user_task_detail_id}` ,task_run_component_type:`${scope.row.task_run_component_type}`,taskType:`${scope.row.task_run_component_type}` } }">{{scope.row.user_task_detail_id}}</router-link>
            <router-link v-else
                         :to="{path:`/${getToPage(scope.row)}` , query:{task_real_id:`${scope.row.task_real_id}`,user_task_detail_id:`${scope.row.user_task_detail_id}` ,task_run_component_type:`${scope.row.task_run_component_type}`,taskType:`${scope.row.task_run_component_type}` } }">{{scope.row.user_task_detail_id}}</router-link>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="user_task_id"
        label="模板名称">
      </el-table-column>
      <el-table-column
        prop="operator_user_name"
        label="操作用户">
      </el-table-column>
      <el-table-column label="状态">
        <template scope="scope">
          <span v-if="scope.row.task_status == '3'">
            <el-tag :type="scope.row.task_result=='2'?`danger`:`success`">
              {{scope.row.task_result | taskResult}}
            </el-tag>
          </span>
          <span v-else>{{scope.row.task_status | taskRunState}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="is_missing"
        label="丢失">
        <template scope="scope">
          <span>{{scope.row.is_missing | isMissing}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="start_time"
        label="开始时间">
      </el-table-column>
      <el-table-column
        prop="end_time"
        label="结束时间">
        <template scope="scope">
          <el-progress v-if="!scope.row.end_time"
                       :text-inside="true"
                       :stroke-width="18"
                       :percentage="70">
          </el-progress>
          <span v-if="scope.row.end_time">{{scope.row.end_time}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="duration_time"
        label="持续时间">
        <template scope="scope">
          <span v-if="scope.row.end_time">{{compareTime(scope.row.start_time, scope.row.end_time)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260px">
        <template scope="scope">
          <el-button type="info" size="small" @click="handleLog(scope)"
                     :disabled="(scope.row.task_status == 4 )">日志
          </el-button>
          <el-button type="info" size="small" @click="downloadLog(scope)"
                     :disabled="(scope.row.task_status == 4 )">下载
          </el-button>
          <el-button type="primary" size="small"
                     :disabled="(scope.row.task_status == 1 || scope.row.task_status == 4)? fasle:true "
                     @click="stopTaskHttp(scope.row)">停止
          </el-button>

          <el-button v-if="taskType ==8" @click="toPage319(scope.row)" size="small" type="info"
                     :disabled="scope.row.task_status==1 || scope.row.task_status==2 ">详情
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--分页-->
    <el-col :span="24" class="toolbar" style="padding-bottom:10px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.start_index"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pagination.page_count"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.count"
        style="float:right"></el-pagination>
    </el-col>
    <!--logs-->
    <el-dialog :title="formTitle" v-model="dialogFormVisible">
      <pre style="white-space: pre-wrap;word-wrap: break-word;">{{txtlog}}</pre>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
  import util from '../../common/util'
  import dao from '../../common/dao'
  import {store} from 'vuex'
  import Search from '../../components/Search.vue'

  export default {
    components: {Search},
    data() {
      return {
        dialogFormVisible: false,
        start: true,
        logs: false,
        tableTitle: [{
          key: 'id',
          name: 'Id',
        }, {
          key: 'status',
          name: '状态',
        }, {
          key: 'startDate',
          name: '开始时间',
        }
        ],
        tableData: [],
        infos: [],
        pagination: {
          count: 0,
          start_index: 1,
          page_count: 20,
        },
        userTaskArg: {},
        txtlog: '',
        formTitle: '',
        task_run_component_type: '',
        taskType: '',
        funGetTaskDetail: 'getTaskDetail',
        funGetByTaskID: 'getByTaskID',
        allTaskDetail: false,
        formInline: {
          allOpts: [{
            key: 'template_name_like',
            label: '模板名称',
            type: '',
            val: ''
          }, {
            key: 'user_task_detail_id',
            label: '任务名称',
            type: '',
            val: ''
          }, {
            key: 'operator_user_name',
            label: '操作用户',
            type: '',
            val: ''
          },{
            key: 'startTime',
            label: '开始时间',
            type: 'datetimerange',
            val: [new Date(new Date().toLocaleDateString()), new Date()]
          },{
            key: 'endTime',
            label: '结束时间',
            type: 'datetimerange',
            val: [new Date(new Date().toLocaleDateString()), new Date()]
          }, {
            key: 'is_missing',
            label: '是否丢失',
            type: 'sel',
            selOption: [{
              label: "否",
              value: "0"
            }, {
              label: "是",
              value: "1"
            }],
            val: ''
          }, {
            key: 'task_status',
            label: '状态',
            type: 'sel',
            selOption: [{
              label: "未运行",
              value: "0"
            }, {
              label: "运行中",
              value: "1"
            }, {
              label: "手动终止",
              value: "2"
            }, {
              label: "提交中",
              value: "4"
            }, {
              label: "成功",
              value: "3"
            },{
              label: "失败",
              value: "5"
            }],
            val: ''
          }/*,{
           key: 'task_run_component_type',
           label: '模版类型',
           type: 'sel',
           selOption: [{
           label: "Spark",
           value: "1"
           }, {
           label: "MapReduce",
           value: "2"
           }, {
           label: "Hive",
           value: "3"
           }, {
           label: "Sqoop",
           value: "4"
           }, {
           label: "Shell",
           value: "5"
           }, {
           label: "工作流",
           value: "6"
           }, {
           label: "Python",
           value: "7"
           }],
           val: ''
           }*/],
          cOpts: [{
            key: 'template_name_like',
            label: '模板名称',
            type: '',
            val: ''
          },{
            key: 'startTime',
            label: '开始时间',
            type: 'datetimerange',
            val: [new Date(new Date().toLocaleDateString()), new Date()]
          },]
        },
      }
    },
    methods: {
      pageInit () {
        //获取页面跳转过来传参

        let query = this.$store.state.route.query || {};

        if (query.allTaskDetail) {
          this.allTaskDetail = true;
          this.getTaskDetailHttp();
          return false
        } else {

          this.userTaskArg = query.parm;
          this.task_run_component_type = query.type
          this.taskType = query.taskType || query.type

          if (query.taskType == '8') {
            this.funGetTaskDetail = 'auditDetail';
            this.funGetByTaskID = 'auditGetDesc'

          }
          this.getByTaskID();
          this.getTaskDetailHttp();
        }
      },
      search(val){
        this.getTaskDetailHttp();
      },
      /**
       * mr,spark,shell,sqoop
       点击id，带入参数task_id,跳到yarn应用page33
       hive
       点击ID，进入tez任务列表，可以点击dag name和application id, dag name 进入dag detail,dag count
       application id 进入yarn application界面/page331
       python
       无法点击id
       工作流
       不变

       1:spark
       2:mapreduce
       3:hive
       4:sqoop
       5:shell
       6:ooz
       7:python
       8:hive sql 稽查任务

       * */
      getToPage (row = {}) {

        //页面跳转
        let toPage33 = ["1", "2", "4", "5"];
        let toPage317 = ["3", "8"];
        let toPage315 = ["6"];
        let type = row.task_run_component_type+''

        let topage = '';
        if (toPage33.indexOf(type) > -1) topage = 'page33';
        else if (type == 3) topage = 'page317';
        else if (type == 6) topage = 'page315';
        else topage = 'page331';
        return topage
      },
      getTopageByID(row){
        if (/[/s/S]*W$/.test(row.task_real_id))return 'page3152';
        else if (/[/s/S]*C$/.test(row.task_real_id)) return 'page315'
      },
      getByTaskID(){
        let fun = this.funGetByTaskID;
        let user_task_id = this.$store.state.route.params.id || '';
        let body = {user_task_ids: [user_task_id]}


        dao[fun](body).then(res => {
          if (res.FX.err) return false;
          let results = res.body.results[0] || {};
          this.infos = results
        })

      },
      handleSizeChange (val) {
        this.pagination.page_count = val;
        this.getTaskDetailHttp();
      },
      handleCurrentChange (val) {

        this.pagination.start_index = val;
        this.getTaskDetailHttp();

      },
      handleSelectionChange () {

      },
      viewLog (val) {
        this.logs = true
      },
      changeStart (i) {
        this.tableData[i].start = this.tableData[i].start == '1' ? "0" : "1";
      },
      handleLog (scope) {
        //展示日志

        let fun = "getLogByTaskId"
        if ((this.$store.state.route.query || {}).taskType == "8") fun = "getAuditTaskLog";

        dao[fun]({task_id: scope.row.user_task_detail_id}).then(res => {
          if (res.FX.err) return false;
          this.txtlog = res.body.file_content
          this.formTitle = `${scope.row.user_task_detail_id} 日志`;
          this.dialogFormVisible = true
        });
        /*if (scope.row.isfile) {
         dao.readFile({hdfs_path: scope.row.txtlog || ''}).then(res => {
         if (res.FX.err) return false;
         this.txtlog = res.body.file_content
         })
         } else this.txtlog = scope.row.txtlog || '';
         this.formTitle = `${scope.row.user_task_detail_id} 日志`;
         this.dialogFormVisible = true*/
      },
      /**
       * 查询任务运行记录列表
       */
      getTaskDetailHttp () { //任务运行详情 请求

        let user_task_id = this.$store.state.route.params.id || ''
        let arg = {
          "start_index": this.pagination.start_index,
          "page_count": this.pagination.page_count
        }

        if (this.allTaskDetail) {
          let cOpts = this.formInline.cOpts

          cOpts.map(item => {
            arg[item.key] = item.val
          })
          let st = arg.startTime||[]
          let et = arg.endTime||[]
          arg.start_time_begin = st[0]?st[0].getTime():void 0;
          arg.start_time_end = st[1]?st[1].getTime():void 0;
          arg.end_time_begin = et[0]?et[0].getTime():void 0;
          arg.end_time_end = et[1]?et[1].getTime():void 0;
        } else arg.user_task_id = user_task_id;


        let fun = this.funGetTaskDetail;
        dao[fun](arg).then((res) => {
          if (res.FX.err) return false;
          this.pagination.count = res.body.count;
          this.tableData = res.body.results;
        })
      },
      compareTime(date1, date2){
        date1 = new Date(date1);
        date2 = new Date(date2);
        let date3 = date2.getTime() - date1.getTime()  //时间差的毫秒数
        //计算出相差天数
        let days = Math.floor(date3 / (24 * 3600 * 1000))
        //计算出小时数
        let leave1 = date3 % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
        let hours = Math.floor(leave1 / (3600 * 1000));
        //计算相差分钟数
        let leave2 = leave1 % (3600 * 1000);       //计算小时数后剩余的毫秒数
        let minutes = Math.floor(leave2 / (60 * 1000));

        //计算相差秒数
        let leave3 = leave2 % (60 * 1000);    //计算分钟数后剩余的毫秒数
        let seconds = Math.round(leave3 / 1000);
        return `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
      },
      stopTaskHttp(row){ //停止任务请求
        this.$confirm('确定要停止该任务吗？, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          row || (row = {})
          let user_task_id = row.user_task_detail_id || undefined;
          let task_real_id = row.task_real_id || undefined;
          let query = this.$store.state.route.query || {};
          let fun = "stopTask"
          if (query.taskType == "8") fun = "stopAuditTask"
          dao[fun]({user_task_id, task_real_id}).then((res) => {
            if (res.FX.err) return false;
            util.callbackTips(res.body);
            this.getTaskDetailHttp()
          })
        });
      },
      toPage319(row){
        this.$router.push({path: '/page319', query: {hdfs_dir: row.data_file_path || ''}}); },
      downloadLog(scope){
        this.$confirm('确定要下载日志文件文件吗?', '提示', {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
         }).then(() => {
          dao.downloadLog({task_id:scope.row.user_task_detail_id},this.taskType == 8)
        }).catch(() => { });
      }
    },
    mounted: function () {

      this.pageInit();


    }
  }
</script>

<style scoped>
  .box-card {
    margin-bottom: 15px;
  }

  .el-message-box {
    width: 800px !important;
  }

  .item {
    margin: 7px 0;
    width: 49%;
    display: inline-block;
  }
</style>